package biz.yfsoft.app.fastframework.api.m;

import biz.yfsoft.app.fastframework.bo.MetaObject;
import biz.yfsoft.app.fastframework.core.Fast;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;

public class TaskM {
	
	/**
	 * * 2.创建一个新的task	任务状态置为 QUEUEING
	 * 3.获取远程的文件	任务状态置为 DOWNLOADING
	 * 4.解压数据文件		任务状态置为 UNZIPING
	 * 5.加载到内存		任务状态置为 LOADING
	 * 6.同步到数据库中	任务状态置为 SYNCING
	 */
	public static final int QUEUEING = 0;
	public static final int DOWNLOADING = 1;
	public static final int UNZIPING = 2;
	public static final int LOADING = 3;
	public static final int SYNCING = 4;
	public static final int FINISHED = 100;
	public static final int ERROR = -1;
	
	private static DbPro apiDb = Db.use("biz"); 
	
//	private static DbPro ecDb = Db.use("ec");

	private TaskM(MetaObject _record){
		this.record = _record;
	}
	
	private MetaObject record = null;
	
	public <T> T get(String k ){
		return record.get(k);
	}
	
	public static TaskM create(String type,String key,String mode) {
		MetaObject record = new MetaObject();
		record.set("type", type);
		record.set("key", key);
		record.set("mode", mode);
		record.create();
		
		if(!apiDb.save("tk_task", record)){
			//保存失败
			return null;
		}
		return new TaskM(record);
	}
	
	
	public void update(int status,Runnable cb){
		record.setStatus(status);
		if(FINISHED == status){
			//保存完成时间
			record.set("finishAt", System.currentTimeMillis());
		}
		if(apiDb.update("tk_task", record)){
			if(cb!=null){
				Fast.AynTask(cb);
			}
		};
		
	}
	
	//执行到了错误
	public void error(String err){
		record.set("status",ERROR);
		record.set("err",err);
		record.set("finishAt", System.currentTimeMillis());
		apiDb.update("tk_task", record);
	}
	
	public static TaskM getTask(int id){
		//查询出任务信息
		Record r = apiDb.findById("tk_task", id);
		MetaObject record = new MetaObject().create(r.getColumns());
		return new TaskM(record);
	}
	
}
